package br.ufal.ic.fracao.agent.resolution.operation.addition;

import java.io.IOException;

import org.jdom.JDOMException;

import br.ufal.ic.fracao.especialist.domain.Item;
import br.ufal.ic.fracao.especialist.inference.InferenceAlgorithm;

public class AdditionAdapter {
	
	public String getSolution(int n1, int d1, int n2, int d2) throws IOException, JDOMException{
		InferenceAlgorithm algorithm = new InferenceAlgorithm();
		
		boolean equalDenominator = false;
		if(d1 == d2){
        	equalDenominator = true;
        }
		
		Item fato1 = new Item();
        fato1.setDescription("Denominador Iqual");
        fato1.setValue(String.valueOf(equalDenominator));
        fato1.setCertaintyFactor(0.2);
        algorithm.addToMemoryWorking(fato1);
        
        
        Item conclusion1 = new Item("(n1+n2)/d1", "true");
        String result1 = algorithm.doForwardChaining(conclusion1, false);
        
        Item conclusion2 = new Item("((mmc/d1)*n1+(mmc/d2)*n2)/mmc", "true");
        String result2 = algorithm.doForwardChaining(conclusion2, false);
        
        if (result1.equalsIgnoreCase("(n1+n2)/d1")) {
        	int numerator = (n1 + n2);
        	if(d1 == 1){
        		return String.valueOf(numerator);
        	}else{
        		return numerator + "/" + d1;
        	}
        }else{
        	if(result2.equalsIgnoreCase("((mmc/d1)*n1+(mmc/d2)*n2)/mmc")){
        		int mmc = this.mmc(d1, d2);
        		int numerator = (mmc/d1)*n1 + (mmc/d2)*n2;        		 
            	if(mmc == 1){
            		return String.valueOf(numerator);
            	}else{
            		return numerator + "/" + mmc;
            	}
        	}
        }
		return null;
	}
	
	public int mmc(int m, int n){
		int x = m;
		int y = n;
		int div = 2;
		int mmc = 1;
		while((x != 1) || (y != 1)){
			while((x % div == 0) || (y % div == 0)){
				mmc = mmc * div;
				if(x % div == 0){
					x = (int)x/div;
				}
				if(y % div == 0){
					y = (int)y/div;
				}
			}
			div++;
		}
		return mmc;
	}
}
